package edu.utsa.cs.contactmanager.views;

import edu.utsa.cs.contactmanager.Contact;
import edu.utsa.cs.contactmanager.ContactManager;
import edu.utsa.cs.contactmanager.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class View_SingleContact extends Activity{
	
	private Contact contact;
	
	ImageView image;
	
	TextView name, phone, email, blacklisted;
    
	Button callButton, textButton, emailButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_single_contact);
        Intent i = getIntent();
        contact = (Contact)i.getSerializableExtra("contact");
        
	}
	
	@Override
    public void onResume(){
    	ContactManager.open();
    	setFields();
    	super.onResume();
    };
    
    @Override
    public void onPause(){
    	ContactManager.close();
    	super.onPause();
    }
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.view_single_contact, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_remove:
        	delete();
        	return true;
        case R.id.action_edit:
        	edit();
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
	
	private void setFields(){
		//Get the contact here!
		
		contact = ContactManager.getContacts(contact.getID()).get(0);
        
		image = (ImageView)findViewById(R.id.image);
		
		BitmapFactory.Options ops = new BitmapFactory.Options();//Saves a ton of memory, decreases image quality though.
		ops.inSampleSize = 16;
		ops.inPreferredConfig = Config.RGB_565;
		Bitmap bmp = BitmapFactory.decodeFile(contact.getPicture(), ops);
		
		
		System.out.println("Loading picture: " + contact.getPicture());
		image.setImageBitmap(bmp);
		
		name = (TextView)findViewById(R.id.nameField);
		name.setText(contact.getFirstName() + " " + contact.getLastName());		
        
		blacklisted = (TextView)findViewById(R.id.blacklisted);
		blacklisted.setText("");
		if(contact.isBlackListed()){
			blacklisted.setText("Contact is blacklisted.");
		}
		
		
		/*
		 * Get ready for this hack!
		 * Displays all phone numbers and buttons to call/text them.
		 */
		
		LinearLayout phoneNumbers = (LinearLayout) findViewById(R.id.phoneNumbers);
		phoneNumbers.removeAllViews();
		
		TextView number;
		Button callB, textB;
		int i = 100;
		
		if(contact.getPhoneNums().size()>0){
			for(String p : contact.getPhoneNums()){
				final String fp = p;
				number = new TextView(this);
				number.setText(p);
				number.setId(i++);
				
				
				callB = new Button(this);
				callB.setText("Call");
				callB.setOnClickListener(new View.OnClickListener() {		
					@Override
					public void onClick(View v) {
						call(fp);
					}
				});
				callB.setId(i++);
				
				textB = new Button(this);
				textB.setText("Text");
				textB.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						text(fp);						
					}
				});
				textB.setId(i++);
				
				LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
				
				LinearLayout numberView = new LinearLayout(this);
				numberView.setId(i++);
				numberView.setOrientation(LinearLayout.HORIZONTAL);
				
				phoneNumbers.addView(numberView, par);
				
				numberView.addView(number, par);
				numberView.addView(callB, par);
				numberView.addView(textB, par);
			}
		}
		
		LinearLayout emailLayout = (LinearLayout) findViewById(R.id.email);
		emailLayout.removeAllViews();
        
        if(contact.getEmail()!=null && !contact.getEmail().equals("")){
        	TextView emailAddr;
    		
    		emailAddr = new TextView(this);
    		emailAddr.setText(contact.getEmail());
    		emailAddr.setId(i++);
    		emailAddr.setTextColor(Color.parseColor("#0000FF"));
    		emailAddr.setClickable(true);
    		emailAddr.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					email(contact.getEmail());
				}
			});
    		
    		LinearLayout.LayoutParams par = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    		emailLayout.addView(emailAddr, par);
        }
        

        
	}
	
	
	
	private void edit(){
		Intent i = new Intent(this, View_EditSingleContact.class);
        i.putExtra("contact", contact);
        startActivity(i);
	}
	
	private void delete(){
		
		new AlertDialog.Builder(this)
	    .setTitle("Delete Contact")
	    .setMessage("Are you sure you want to delete this contact?")
	    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) { 
	        	ContactManager.removeContactById(contact.getID());
	        	
	        	Context context = getApplicationContext();
	        	CharSequence text = "Contact Deleted";
	        	int duration = Toast.LENGTH_LONG;

	        	Toast toast = Toast.makeText(context, text, duration);
	        	toast.show();
	        	
	        	onBackPressed();
	        }
	     })
	    .setNegativeButton("No", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) { 
	            // do nothing
	        }
	     })
	     .show();		
	}
	
	private void email(String s){
		Intent intent = new Intent(Intent.ACTION_SENDTO);
		intent.setData(Uri.parse("mailto:" + s));
		startActivity(intent);
	}
	
	private void text(String s){
		Intent smsIntent = new Intent(Intent.ACTION_VIEW);
		smsIntent.setType("vnd.android-dir/mms-sms");
		smsIntent.putExtra("address", s);
		try{
			startActivity(smsIntent);
		}
		catch(Exception e){
			new AlertDialog.Builder(this)
		    .setTitle("Warning")
		    .setMessage("No software available to handle texting.")
		    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int which) {
		        }
		     })
		     .show();
		}
		
	}
	
	private void call(String s){
		String uri = "tel:" + s;
		Intent intent = new Intent(Intent.ACTION_DIAL);
		intent.setData(Uri.parse(uri));

		try{
			startActivity(intent);
		}
		catch(Exception e){
			new AlertDialog.Builder(this)
		    .setTitle("Warning")
		    .setMessage("No software available to handle calling.")
		    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int which) {
		        }
		     })
		     .show();
		}
	}

}
